Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Course Overview
Basics of Tree
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Level Order Traversal Pattern (easy)
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Reverse Level Order Traversal

Problem Statement

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., the lowest level comes first in left to right order.)

Examples

Example 1

  • Input: root = [1, 2, 3, 4, 5, 6, 7]
Image
  • Expected Output: [[4, 5, 6, 7], [2, 3], [1]]
  • Justification:
    • The third level has 4, 5, 6, and 7 nodes.
    • The second level has 2 and 3 nodes.
    • The first level has a single node with the value 1.

Example 2

  • Input: root = [12, 7, 1, null, 9, 10, 5]
Image
  • Expected Output: [[9, 10, 5], [7, 1], [12]]
  • Justification:
    • The third level has 9, 10, and 5 nodes.
    • The second level has 7 and 1 nodes.
    • The first level has a single node with the value 12.

Example 3

  • Input: root = [6,5,2,null,null,1,6,3,56,3]
Image
  • Expected Output: [[3,56,3],[1,6],[5,2],[6]]
  • Justification:
    • The fourth level has 3, 56, and 3 nodes.
    • The third level has 1, and 6 nodes.
    • The second level has 5 and 2 nodes.
    • The first level has a single node with the value 6.

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Solution

To solve the reverse level order traversal problem, we will perform a breadth-first search (BFS) using a queue. The idea is to traverse the tree level by level from top to bottom but store each level's result in reverse order. At each level, we process all nodes, add their values to the current level list, and then enqueue their left and right children. Instead of appending the level at the end of the result, we insert it at the beginning, ensuring that when we finish, the result is in reverse level order.

Step-by-Step Algorithm

  1. Initialization:

    • If the root is null, return an empty list because there is no tree to traverse.
    • Initialize a queue to help with the BFS traversal. The queue will store nodes that need to be processed.
    • Initialize an empty list result to store the final reversed level order traversal.
  2. Start BFS Traversal:

    • Add the root node to the queue. This represents the starting point of the level order traversal.
  3. Process Nodes Level by Level:

    • While the queue is not empty, do the following:
      • Find out how many nodes are on the current level by checking the size of the queue (levelSize = queue.size()).
      • Initialize an empty list currentLevel to store the values of the nodes at this level.
  4. Process Each Node in the Current Level:

    • For each node at the current level, repeat the following steps:
      • Dequeue the front node of the queue.
      • Add the value of the node to the currentLevel list.
      • If the dequeued node has a left child, enqueue the left child.
      • If the dequeued node has a right child, enqueue the right child.
  5. Add the Current Level to the Result:

    • Once all nodes at the current level have been processed, add the currentLevel list to the front of the result list. This ensures that the levels are inserted in reverse order.
  6. Repeat:

    • Repeat the process until all nodes have been processed and the queue is empty.
  7. Return the Final Result:

    • After processing all the levels, return the result list, which contains the node values in reverse level order.

Algorithm Walkthrough

Input: root = [12, 7, 1, null, 9, 10, 5]

Image
  1. Initialization:

    • Root: 12
    • Initialize queue = [12]
    • Initialize result = []
  2. First Level:

    • levelSize = 1 (only one node at this level: 12)
    • Initialize currentLevel = []
    • Dequeue 12, add its value to currentLevel: currentLevel = [12]
    • Enqueue the left child (7) and right child (1): queue = [7, 1]
    • Insert currentLevel at the beginning of result: result = [[12]]
  3. Second Level:

    • levelSize = 2 (two nodes at this level: 7 and 1)
    • Initialize currentLevel = []
    • Dequeue 7, add its value to currentLevel: currentLevel = [7]
    • Enqueue the right child (9), no left child: queue = [1, 9]
    • Dequeue 1, add its value to currentLevel: currentLevel = [7, 1]
    • Enqueue the left child (10) and right child (5): queue = [9, 10, 5]
    • Insert currentLevel at the beginning of result: result = [[7, 1], [12]]
  4. Third Level:

    • levelSize = 3 (three nodes at this level: 9, 10, and 5)
    • Initialize currentLevel = []
    • Dequeue 9, add its value to currentLevel: currentLevel = [9]
    • Dequeue 10, add its value to currentLevel: currentLevel = [9, 10]
    • Dequeue 5, add its value to currentLevel: currentLevel = [9, 10, 5]
    • No more children to enqueue: queue = []
    • Insert currentLevel at the beginning of result: result = [[9, 10, 5], [7, 1], [12]]
  5. Final Result:

    • The queue is now empty, so we return the result.
    • The final reverse level order traversal is [[9, 10, 5], [7, 1], [12]].

Final Output:

  • The reverse level order traversal for the tree [12, 7, 1, null, 9, 10, 5] is [[9, 10, 5], [7, 1], [12]].

Code

Java
Saved to Cloud

. . . .

Time Complexity

The time complexity of the above algorithm is , where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be as we need to return a list containing the level order traversal. We will also need space for the queue. Since we can have a maximum of N/2 nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.

Reverse Level Order Traversal (easy)
Find Largest Value in Each Tree Row (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Final Output:

Code

Time Complexity

Space Complexity